package com.unhz.taigu.controller;

import com.unhz.generator.enums.EnumDeliveryOrder;
import com.unhz.generator.pojo.DeliveryOrder;
import com.unhz.generator.pojo.Logistics;
import com.unhz.generator.utils.*;
import com.unhz.generator.vo.DeliveryOrderVo;
import com.unhz.taigu.service.DeliveryOrderService;
import com.unhz.taigu.service.LogisticsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 王林恩
 * @Description:交货订单
 * @Date: Created in 上午 9:01 2018/2/1 0001
 * @Modified By:
 */
@Controller
@RequestMapping("/deliveryOrder")
public class DeliveryOrderController {

    static final int COMPLETE_DELIVERY = 1;

    private final Logger logger = LoggerFactory.getLogger(DeliveryOrderController.class);

    @Autowired
    private DeliveryOrderService deliveryOrderService;
    //引入物流的service
    @Autowired
    private LogisticsService logisticsService;

    /**
     * 分页查询
     * @param model
     * @param pageNo 页数
     * @param keywords 关键词
     * @return
     */
    @RequestMapping("/findDeliveryOrder")
    public String findAllDeliveryOrder(Model model,
                                       @RequestParam(value = "pageNo",defaultValue = "1",required = false)String pageNo,
                                       @RequestParam(value = "keywords",defaultValue = "",required = false)String keywords,
                                       @RequestParam(value = "adminId",defaultValue = "",required = false)Integer adminId,
                                       @RequestParam(value = "roleId",defaultValue = "",required = false)Integer roleId,
                                       HttpServletRequest request) throws UnsupportedEncodingException {
        if("GET".equals(request.getMethod())){
            keywords = new String(keywords.getBytes("iso-8859-1"),"utf-8");
        }
        Page<DeliveryOrderVo> page = deliveryOrderService.findAllDeliveryOrder(pageNo, PageSize.pageSize,keywords,adminId,roleId);
        model.addAttribute("page",page);
        model.addAttribute("keywords",keywords);
        logger.info("page的大小======"+page.getRecords().size());
        return "delivery/index.jsp";
    }

    @RequestMapping("/findCount")
    @ResponseBody
    public JsonResult findCountDeliveryOrder(@RequestParam(value = "keywords",defaultValue = "",required = false)String keywords){
        int res = deliveryOrderService.findCountDeliveryOrder(keywords);
        return JsonResult.success(res);
    }

    /**
     * 修改交货订单状态
     * @param deliveryOrderId 交货订单id
     * @param status 状态
     * @return
     */
    @RequestMapping("/changeStatus")
    @ResponseBody
    public JsonResult changeStatus(@RequestParam(value="deliveryOrderId")String deliveryOrderId,
                                   @RequestParam(value="status",required = false)String status){
        DeliveryOrder deliveryOrder = deliveryOrderService.findDeliveryOrder(Long.parseLong(deliveryOrderId));
        //状态为1时表示待确认，改变为待出库
        if(!EmptyUtil.isEmpty(status)){
            if(String.valueOf(EnumDeliveryOrder.WAIT_NOTARIZE.getIndex()).equals(status)){
                deliveryOrder.setStatus(Byte.parseByte(String.valueOf(EnumDeliveryOrder.WAIT_OUTPUT.getIndex())));
                deliveryOrderService.updateDeliveryOrder(deliveryOrder);
                return JsonResult.success("确认成功！");
            }
            //状态为2时表示待出库，改变运输中
            if(String.valueOf(EnumDeliveryOrder.WAIT_OUTPUT.getIndex()).equals(status)){
                deliveryOrder.setStatus(Byte.parseByte(String.valueOf(EnumDeliveryOrder.TRANSIT.getIndex())));
                //生成订单号:
                String wayallnum = DateHelper.ContentNowDate(new Date());
                if(!EmptyUtil.isEmpty(deliveryOrder.getCounties())){
                    wayallnum += deliveryOrder.getCounties();
                }else{
                    wayallnum += deliveryOrder.getCity();
                }
                deliveryOrder.setWaybillNo(wayallnum);
                deliveryOrderService.updateDeliveryOrder(deliveryOrder);
                //添加出库信息
                Logistics logistics = new Logistics();
                logistics.setDeliveryId(Long.parseLong(deliveryOrderId));
                logistics.setInfo("已出库");
                int count =  logisticsService.insertLogistics(logistics);
                return JsonResult.success("出库完成！");
            }
            //状态为3时表示运输中，改变为完成交货
        }
        return JsonResult.failure("操作失败！");
    }

    /*
     * 添加交货订单 接口
     * @param deliveryOrder 交货订单
     * @param sizeNumber 码数数量
     * @return
     */
    @RequestMapping("/addDeliveryOrder")
    @ResponseBody
    public JsonResult addDeliveryOrder(DeliveryOrder deliveryOrder,
                                       @RequestParam(value = "",defaultValue = "",required = true) String[] size,
                                       @RequestParam(value = "",defaultValue = "",required = true) String[] number){
        //String sizeNumber ="35#=1200,36#=1200,37#=1200,38#=1200,39#=1200,40#=1200,41#=1200,42#=1200";
        DeliveryOrder deliveryOrder1 = new DeliveryOrder();//模拟参数
        deliveryOrder1.setDeliveryNo("测试123");
        deliveryOrder1.setProductionId(6);
        /*String[] sizeNumbers = sizeNumber.split(",");
        List<String> list = Arrays.asList(sizeNumbers);*/
        int res = deliveryOrderService.addDeliveryOrder(deliveryOrder1,size,number);
        return JsonResult.success(res);
    }

/*    @RequestMapping("/getStrCount")
    @ResponseBody
    public JsonResult getStrCount(String string){
        String[] sizeNumbers = string.split("");
        List<String> list = Arrays.asList(sizeNumbers);
        Set<String> resSet = new HashSet<String>();
        for (int i=0;i<list.size();i++){
            String ss =list.get(i);
            int count = 0;
            for (int j=0;j<list.size();j++){
                if (ss.equals(list.get(j))){
                    count++;
                }
            }
            String res = ss+"出现了"+count+"次";
            resSet.add(res);
        }
        char ch[] = string.toCharArray();
        Map<Character,Integer> map= new  HashMap<Character,Integer>();
        Set<Character>  set=map.keySet();
        for(int i=0;i<ch.length;i++){
            if(set.contains(ch[i])){
                map.put(ch[i],map.get(ch[i])+1);
            }else{
            map.put(ch[i],1);
        }
        }
        Set<Character> set2=map.keySet();
        for(Character character:set2){
            System.out.println(character+"出现了"+map.get(character)+"次");
        }


        return JsonResult.success(resSet);
    }*/

    /*
    * 删除交货订单 接口
    * @param deliveryOrder 交货订单
     * @param sizeNumber 码数数量
     * @return
     */
    @RequestMapping("/deleteDeliveryOrder")
    @ResponseBody
    public JsonResult deleteDeliveryOrder( @RequestParam(value = "deliveryOrderId",defaultValue = "",required = true) String deliveryOrderId){
        int res = deliveryOrderService.deleteDeliveryOrderById(Long.parseLong(deliveryOrderId));
        if(res>0){
            return  JsonResult.success("删除成功！");
        }
        return JsonResult.failure("删除失败！");
    }

    /**
     * 修改交货订单 接口
     * @param deliveryOrder 交货订单
     * @param time  计划交期时间
     * @return
     * @throws ParseException
     */
    @RequestMapping("/updateDeliveryOrder")
    @ResponseBody
    public JsonResult updateDeliveryOrder(DeliveryOrder deliveryOrder, @RequestParam(value= "time",required = false) String time) throws ParseException{
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date planDate = sdf.parse(time);
        deliveryOrder.setDeliveryTime(planDate);
        int res = deliveryOrderService.updateDeliveryOrder(deliveryOrder);
        if (res>0){
            return JsonResult.success("修改成功！");
        }
        return JsonResult.failure("修改失败！");
    }

    /**
     * 跳转到物流详情
     * @param deliveryId
     * @param model
     * @return
     */
    @RequestMapping("/logisticsFind")
    public String logisticsFind(@RequestParam("deliveryId")Integer deliveryId , Model model){

        //查询物流详情
        List<Logistics> logisticsList = logisticsService.selectByDeliveryId(deliveryId);
        if(!EmptyUtil.isEmpty(logisticsList)){
            model.addAttribute("logisticsList",logisticsList);
        }
        return "delivery/logistics-list.jsp";
    }

    /**
     * 异步添加物流信息
     * @param deliveryId
     * @param info
     * @param checkNo
     * @return
     */
    @RequestMapping("/addLogistics")
    @ResponseBody
    public JsonResult addLogistics(@RequestParam("deliveryId")Integer deliveryId,
                                   @RequestParam("info")String info,
                                   @RequestParam("checkNo")Integer checkNo){

        Logistics logistics = new Logistics();
        logistics.setDeliveryId(Long.valueOf(deliveryId));
        logistics.setInfo(info);
        int count = 0;
        if(checkNo == COMPLETE_DELIVERY){
            count = logisticsService.insertLogistics(logistics);
        }else{
            count = logisticsService.insertLogistics(logistics);
            //修改状态(订单完成)(4)
            deliveryOrderService.updateDeliveryOrderStatus(deliveryId,EnumDeliveryOrder.FINISH_DELIVERY.getIndex());
        }
        if (count > 0){
            return JsonResult.success("更新物流成功");
        }
        return JsonResult.failure("更新物流失败");
    }

}
